﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FileManager.Model;
using FileManager.Util;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Xml.Linq;
using System.Drawing;
using TsubakiTranslator.BasicLibrary;

namespace FileManager.ViewModel
{
    internal partial class MainWindowViewModel : ObservableObject
    {
        private bool MinIdx => Idx > 0;
        private bool MaxIdx => Idx < MaxNum - 1;

        /// <summary>
        /// 下一个文件
        /// </summary>
        [RelayCommand(CanExecute = nameof(MinIdx))]
        private void PreFile()
        {
            ModifyFileInfo();
            Idx--;
        }
        /// <summary>
        /// 上一个文件
        /// </summary>
        [RelayCommand(CanExecute = nameof(MaxIdx))]
        private void NextFile()
        {
            ModifyFileInfo();
            Idx++;
        }

        /// <summary>
        /// 从xml文件导入元数据信息
        /// </summary>
        [RelayCommand]
        private void ImpFromXml()
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            openFileDialog.Filter = "*.xml|*.xml";
            openFileDialog.ShowDialog();
            if (openFileDialog.FileNames.Count()==0)
                return;
            string filePath = openFileDialog.FileName;
            Idx = 0;
            oriFiles= FileMetadataUtils.LoadFromFile(filePath);

            oriFiles.ToList().ForEach(a => OfficeHelper.GetWordDocumentSource(ref a));
            Meta2Show = oriFiles.Clone();
            DataPath = filePath;
            if (Meta2Show.Count != 0)
            {
                List<string> tagList = Meta2Show.SelectMany(a => a.Tag).Distinct().ToList() ;
                tagList.ForEach(a => view.AddCheckBox(a));
                if (!tagList.Contains("删除"))
                {
                    tagList.Add("删除");
                    view.AddCheckBox("删除");
                }
                MaxNum= Meta2Show.Count;
                view.Update();
            }

        }
        [RelayCommand]
        private void TEST()
        {

            string filePaht = "C:\\Users\\My\\Desktop\\183254f0-22f1-44c0-8cfc-7325b4ef4324.jpg";
            Bitmap bitmap=new Bitmap(filePaht);
            OcrProgram ocr = new OcrProgram(12);
            var tb=ocr.RecognizeAsync(bitmap).Result;
            Debug.WriteLine(tb);
            //string url = $"http://127.0.0.1:5000/ocr?file_path={filePaht}";
            //WebClient webClient = new WebClient();
            //var t2 = webClient.DownloadString(url);
            //Debug.WriteLine(t2.Trim());
            
            
            //OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            //openFileDialog.Filter = "word文档|*.docx;*.doc";
            //openFileDialog.ShowDialog();
            //if (openFileDialog.FileNames.Count() == 0)
            //    return;
            //string filePath = openFileDialog.FileName;
            //OfficeHelper.GetWordDocumentSource(filePath);

        }
        [RelayCommand]
        private void Search()
        {
            Idx = 0;
            string searchCode = view.tagText.Text.Trim();
            if (searchCode.Split(":").Count()>1)
            {
                string label = searchCode.Split(":")[0];
                string info = searchCode.Substring(label.Length + 1);
                switch(label.ToLower())
                {
                    case "name": Meta2Show = FileMetadataCollection.FromEnumerable(oriFiles.Where(a=>a.FileName.Contains(info))); break;
                    case "tag": Meta2Show = FileMetadataCollection.FromEnumerable(FileMetadataUtils.FindByTag(oriFiles, info));break;

                }
            }
            else
            {
                string targetTags = searchCode;
                Meta2Show = FileMetadataCollection.FromEnumerable(FileMetadataUtils.FindByTag(oriFiles, targetTags));
            }

            if (Meta2Show.Count != 0)
            {
                List<string> tagList = Meta2Show.SelectMany(a => a.Tag).Distinct().ToList();
                tagList.ForEach(a => view.AddCheckBox(a));
                MaxNum = Meta2Show.Count;
                view.Update();
            }
        }


        [RelayCommand]
        private void Rename()
        {
            string nName=view.tagText.Text;
            string nPath=Path.Combine(CurrentFile.ParentPath,nName);
            if (Path.Exists(nPath))
            {
                System.Windows.MessageBox.Show("该文件名已存在，无法改名");
                return;
            }
            if (System.Windows.MessageBox.Show($"是否将文件{CurrentFile.FileName}=>{nName}，是否更改", "变更提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                File.Move(CurrentFile.Path, nPath);

                var fi=oriFiles.First(a=>a.Hash==CurrentFile.Hash);
                int idx=oriFiles.IndexOf(fi);
                oriFiles[idx] = new MetaData(nPath);
                CurrentFile = oriFiles[idx];
            }

        }
        [RelayCommand]
        private void BtnMove()
        {
            if (view.lbFiles.SelectedIndex != -1||view.lbFiles.Items.Count==1)
            {
                List<string> filesToMove = Meta2Show.Select(a => a.FileName).ToList();
                string selectedFile = null;
                if (view.lbFiles.Items.Count == 1)
                    selectedFile = (string)view.lbFiles.Items[0] as string;
                else
                {
                    selectedFile=view.lbFiles.SelectedItem as string;
                }
                if (selectedFile == null)
                    return;
                if (MoveOther)
                {
                    _=filesToMove.Remove(selectedFile); // 移除选中的文件
                }
                else
                {
                    filesToMove = new List<string>() { selectedFile };
                }
                foreach (var file in filesToMove)
                {
                    string sourceFile = file;
                    string fileName = new FileInfo(sourceFile).Name;
                    string destinationFile = Path.Combine(MovePath, fileName);
                    if (File.Exists(sourceFile))
                    {
                        File.Move(sourceFile, destinationFile); // 移动文件到目标文件夹
                    }
                }
                ShowStatusBarMessage("其他文件已移动到目标文件夹。");
            }
            else
            {
                System.Windows.MessageBox.Show("请先选择一个文件。");
                return;
            }
            if(Idx!=MaxNum-1)
                Idx++;
            view.proBar.Value = Idx;
            //fileNames = fileDic.ElementAt(model.Idx).Value.Select(a => a.FullName).ToList();
            //lbFiles.ItemsSource = fileNames;
        }

        /// <summary>
        /// 清点比对，查询出哪些文件名已经更改
        /// </summary>
        [RelayCommand]
        private void CheckClear()
        {
            OpenFolderDialog openFolderDialog = new OpenFolderDialog();
            if (!openFolderDialog.ShowDialog().HasValue)
                return;
            string folderPath = openFolderDialog.FolderName;
            var allFiles = MainWindow.TraverseAndPrintFiles(folderPath);

            var newMetaCollection = FileMetadataCollection.FromEnumerable(from file in allFiles select new MetaData(file));
            var duplicatesWithDifferentNames = Meta2Show.Join(
                newMetaCollection,
                meta1 => meta1.Hash,
                meta2 => meta2.Hash,
                (meta1, meta2) => new { oldMate = meta1, newMate = meta2 })
                .Where(pair => pair.oldMate.FileName != pair.newMate.FileName)
                .ToList();

            // 输出结果
            foreach (var pair in duplicatesWithDifferentNames)
            {
                Debug.WriteLine($"Found matching hashes but different names: {pair.oldMate.FileName} and {pair.newMate.FileName}");
                if(System.Windows.MessageBox.Show($"文件已更名{pair.oldMate.FileName}=>{pair.newMate.FileName}，是否更改","变更提示",MessageBoxButton.YesNo)== MessageBoxResult.Yes)
                {
                    FileMetadataUtils.UpdateFileMetadata(DataPath,pair.newMate);
                }
            }
            var delName= Meta2Show.Where(a=>newMetaCollection.Where(b=>a.Hash==b.Hash).Count()==0).ToList();
            foreach (var del in delName)
            {
                FileMetadataUtils.RemoveFileMetadata(DataPath, del);
                Debug.WriteLine($"这些文件已被删除: {del.FileName}");
            }
        }




        private void ShowStatusBarMessage(string message)
        {
            StatusBarMessage = message;
            IsStatusBarMessageVisible = true;
            _statusBarTimer.Start();
        }

        private void OnStatusBarTimerTick(object sender, EventArgs e)
        {
            ClearStatusBarMessage();
        }

        private void ClearStatusBarMessage()
        {
            StatusBarMessage = "";
            IsStatusBarMessageVisible = false;
            _statusBarTimer.Stop();
        }

        // 示例：在某个命令中显示提示信息
        public RelayCommand ShowInfoCommand { get; }
        private void ExecuteShowInfoCommand()
        {
            ShowStatusBarMessage("提示信息将在2秒后消失");
        }

        /// <summary>
        /// 修改保存当前项的MetaData
        /// </summary>
        private void ModifyFileInfo()
        {
            if (null != Meta2Show[Idx].Tag)
                Meta2Show[Idx].Tag.Clear();
            Meta2Show[Idx].Tag = new List<string>();
            foreach (System.Windows.Controls.CheckBox check in view.CheckBoxPanel.Children)
            {
                if (check != null && check.IsChecked == true)
                {
                    string tagStr = check.Content.ToString() ?? "";
                    if (tagStr.Length > 0 && !Meta2Show[Idx].Tag.Contains(tagStr))
                        Meta2Show[Idx].Tag.Add(tagStr);
                }
            }
            Debug.WriteLine(Meta2Show[Idx].FileName);
            Debug.WriteLine(String.Join(",", Meta2Show[Idx].Tag));
            FileMetadataUtils.UpdateFileMetadata(DataPath, Meta2Show[Idx]);
        }
        private void SaveFileInfo()
        {
            foreach (System.Windows.Controls.CheckBox check in view.CheckBoxPanel.Children)
            {
                if (check != null && check.IsChecked == true)
                {
                    string tagStr = check.Content.ToString() ?? "";
                    if (tagStr.Length > 0 && !Meta2Show[Idx].Tag.Contains(tagStr))
                        Meta2Show[Idx].Tag.Add(tagStr);
                }
            }
            Debug.WriteLine(Meta2Show[Idx].FileName);
            Debug.WriteLine(String.Join(",", Meta2Show[Idx].Tag));
            FileMetadataUtils.SaveToFile(Meta2Show, DataPath);
        }
    }
}
